﻿using iText.Forms;
using iText.Kernel.Pdf;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WordCounter.Core
{
    public class PageCounter
    {
        /// <summary>
        /// 统计word页数
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static long CountWordPage(string filename)
        {
            Application wordApp = null;
            Document doc = null;
            object missing = Missing.Value;
            long pages = 0L;

            try
            {
                wordApp = new Application();
                doc = wordApp.Documents.Open(filename, missing);
                pages = doc.ComputeStatistics(WdStatistic.wdStatisticPages, ref missing);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                    doc.Close(false, Type.Missing, Type.Missing);

                if (wordApp != null)
                    wordApp.Quit(false, Type.Missing, Type.Missing);

                GC.Collect();
            }

            return pages;
        }

        /// <summary>
        /// 获取PDF文件页数
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static long CountPDFPage(string filename)
        {
            long count = 0;
            using(PdfReader reader = new PdfReader(filename))
            {
                using(PdfDocument doc = new PdfDocument(reader))
                {
                    PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, false);
                    count = doc.GetNumberOfPages();
                }
            }
            return count;
        }
    }
}
